﻿using Newtonsoft.Json;
using System;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace Sustainalytics.Utils
{
    public class LogControllerFilter : ActionFilterAttribute
    {
        private static string __duration = "__duration";

        public LogControllerFilter(bool inout, bool arguments, bool output)
        {
        }

        public LogControllerFilter()
        {
        }

        public override void OnActionExecuting(HttpActionContext actionExecutedContext)
        {
            if (actionExecutedContext.ActionArguments != null)
                actionExecutedContext.ActionArguments[__duration] = DateTime.Now;
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var statusCode = string.Empty;
            var reasonPhrase = string.Empty;
            var args = string.Empty;
            var output = "null";
            string duration;
            var start = DateTime.MaxValue;

            var ctrlName = actionExecutedContext.ActionContext.ControllerContext.Controller.ToString();
            var methName = actionExecutedContext.Request.Method.ToString();
            var requestUri = actionExecutedContext.Request.RequestUri.ToString();

            if (actionExecutedContext.Response != null)
            {
                statusCode = ((int)actionExecutedContext.Response.StatusCode).ToString();
                reasonPhrase = actionExecutedContext.Response.ReasonPhrase;
            }

            if (actionExecutedContext.ActionContext.ActionArguments != null)
            {
                if (actionExecutedContext.ActionContext.ActionArguments.ContainsKey(__duration))
                {
                    start = (DateTime)actionExecutedContext.ActionContext.ActionArguments[__duration];
                    actionExecutedContext.ActionContext.ActionArguments.Remove(__duration);
                }
                args = JsonConvert.SerializeObject(actionExecutedContext.ActionContext.ActionArguments);

                if (args.Length > 1024)
                    args = args.Substring(0, 1024);
            }

            duration = (DateTime.Now - start).TotalMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture);

            CommonEventSource.Log.WebRequestActivity(ctrlName, methName, requestUri, statusCode, reasonPhrase, args, output, duration, null);
        }
    }
}
